package com.yami.shop.api.controller.app;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.app.dto.PostRecordDto;
import com.yami.shop.bean.app.param.PostRecordParam;
import com.yami.shop.bean.model.PostLikeRecord;
import com.yami.shop.bean.model.PostRecord;
import com.yami.shop.bean.model.User;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.dao.PostRecordMapper;
import com.yami.shop.dao.UserLikeRecordMapper;
import com.yami.shop.security.util.SecurityUtils;
import com.yami.shop.service.PostLikeRecordService;
import com.yami.shop.service.PostRecordService;
import com.yami.shop.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 动态记录 前端控制器
 * </p>
 *
 * @author chajiu
 * @since 2021-06-28
 */
@RestController
@RequestMapping("/p/post-record")
@Api(tags = "动态接口")
public class PostRecordController {


    @Autowired
    private PostRecordService postRecordService;
    @Autowired
    private PostRecordMapper postRecordMapper;
    @Autowired
    private MapperFacade mapperFacade;
    @Autowired
    private PostLikeRecordService postLikeRecordService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserLikeRecordMapper userLikeRecordMapper;


    @PostMapping("/like/{id}")
    @ApiOperation(value = "添加动态喜欢", notes = "添加动态喜欢")
    public ResponseEntity<Void> page(@PathVariable(value = "id") String postId) {
        String userId = SecurityUtils.getUser().getUserId();
        PostLikeRecord one = postLikeRecordService.getOne(Wrappers.lambdaQuery(new PostLikeRecord())
                .eq(PostLikeRecord::getPostId, postId)
                .eq(PostLikeRecord::getUserId, userId));
        if (one != null) {
            return ResponseEntity.ok().build();
        }

        // 添加喜欢记录
        PostLikeRecord p = new PostLikeRecord();
        p.setCreateTime(new Date());
        p.setPostId(postId);
        p.setUserId(userId);
        postLikeRecordService.save(p);

        //添加动态喜欢数量
        postRecordMapper.addOnePostLike(postId);
        return ResponseEntity.ok().build();
    }

    @PostMapping("/canceLike/{id}")
    @ApiOperation(value = "取消动态喜欢", notes = "取消动态喜欢")
    public ResponseEntity<Void> cancelLike(@PathVariable(value = "id") String postId) {
        String userId = SecurityUtils.getUser().getUserId();

        PostLikeRecord onee = postLikeRecordService.getOne(Wrappers.lambdaQuery(new PostLikeRecord())
        .eq(PostLikeRecord::getPostId, postId));
        PostLikeRecord one = postLikeRecordService.getOne(Wrappers.lambdaQuery(new PostLikeRecord())
                .eq(PostLikeRecord::getPostId, postId)
                .eq(PostLikeRecord::getUserId, userId));
        if (one == null) {
            return ResponseEntity.ok().build();
        }

        // 删除喜欢记录
        postLikeRecordService.remove(Wrappers.lambdaQuery(new PostLikeRecord())
            .eq(PostLikeRecord::getPostId,postId)
            .eq(PostLikeRecord::getUserId,userId));

        //减少动态喜欢数量
        postRecordMapper.subOnePostLike(postId);
        return ResponseEntity.ok().build();
    }




    /**
     * 分页获取
     */
    @GetMapping("/page")
    @ApiOperation(value = "获取动态页列表", notes = "获取动态页列表")
    public ResponseEntity<IPage<PostRecord>> page(PageParam<PostRecord> page) {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        IPage<PostRecord> iPage = postRecordService.page(page, new LambdaQueryWrapper<PostRecord>()
                //.inSql(user.getSex().equals("M"),PostRecord::getUserId,"select user_id from tz_user where sex = 'F'")
                .eq(PostRecord::getStatus, 1)
                .eq(PostRecord::getIsDel, 0)
                .orderByDesc(PostRecord::getCreateTime));
        List<PostRecord> records = iPage.getRecords();
        for (PostRecord record : records) {
            User one = userService.getById(record.getUserId());
            record.setUserName(one.getNickName());
            record.setUserPic(one.getPic());
            record.setAge(one.getAge());
            record.setSex(one.getSex());
            if(postLikeRecordService.isLiked(userId,record.getId())){
                record.setIsLiked(1);
            }else{
                record.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(iPage);
    }

    /**
     * 获取附近50km内动态
     */
    @GetMapping("/nea")
    @ApiOperation(value = "获取附近动态列表", notes = "获取附近动态页列表")
    public ResponseEntity<List<PostRecordDto>> getNeaMove() {
        String userId = SecurityUtils.getUser().getUserId();
        User user = userService.getById(userId);
        List<PostRecordDto> records = new ArrayList<>();
        if(1==2){//user.getSex().equals("M")
            if(user.getLng() != null || user.getLat() != null){
                records = userLikeRecordMapper.queryNeaMoveUserSex(user.getLng(),user.getLat());
            }else {
                records = userLikeRecordMapper.queryRegionSex(user.getProvince());
            }
        }else {
            if(user.getLng() != null || user.getLat() != null){
                records = userLikeRecordMapper.queryNeaMoveUser(user.getLng(),user.getLat());
            }else {
                records = userLikeRecordMapper.queryRegion(user.getProvince());
            }
        }


        for (PostRecordDto record : records) {


            if(postLikeRecordService.isLiked(userId,record.getId())){
                record.setIsLiked(1);
            }else{
                record.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(records);
    }

    @GetMapping("/one/page")
    @ApiOperation(value = "分页获取登录用户的动态", notes = "分页获取登录用户的动态")
    public ResponseEntity<IPage<PostRecord>> pageByOne(PageParam<PostRecord> page) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<PostRecord> iPage = postRecordService.page(page, Wrappers.lambdaQuery(new PostRecord())
                .eq(PostRecord::getUserId, userId)
                .eq(PostRecord::getStatus,1)
                .eq(PostRecord::getIsDel, 0)
                .orderByDesc(PostRecord::getCreateTime));
        List<PostRecord> records = iPage.getRecords();
        for (PostRecord record : records) {
            User one = userService.getById(record.getUserId());
            record.setUserName(one.getNickName());
            record.setUserPic(one.getPic());
            record.setAge(one.getAge());
            record.setSex(one.getSex());
            if(postLikeRecordService.isLiked(userId,record.getId())){
                record.setIsLiked(1);
            }else{
                record.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(iPage);
    }


    @GetMapping("/{id}/page")
    @ApiOperation(value = "分页获取某用户的动态", notes = "分页获取某用户的动态")
    public ResponseEntity<IPage<PostRecord>> pageByUid(PageParam<PostRecord> page,@PathVariable("id") String targetUid) {
        String userId = SecurityUtils.getUser().getUserId();
        IPage<PostRecord> iPage = postRecordService.page(page, Wrappers.lambdaQuery(new PostRecord())
                .eq(PostRecord::getUserId, targetUid)
                .eq(PostRecord::getStatus,1)
                .eq(PostRecord::getIsDel, 0)
                .orderByDesc(PostRecord::getCreateTime));
        List<PostRecord> records = iPage.getRecords();
        for (PostRecord record : records) {
            User one = userService.getById(record.getUserId());
            record.setUserName(one.getNickName());
            record.setUserPic(one.getPic());
            record.setAge(one.getAge());
            record.setSex(one.getSex());
            if(postLikeRecordService.isLiked(userId,record.getId())){
                record.setIsLiked(1);
            }else{
                record.setIsLiked(0);
            }
        }
        return ResponseEntity.ok(iPage);
    }

    /**
     * 获取信息s
     */
    @GetMapping("/info/{id}")
    @ApiOperation(value = "获取动态详情", notes = "获取动态详情")
    public ResponseEntity<PostRecord> info(@PathVariable("id") String id) {

        String userId = SecurityUtils.getUser().getUserId();
        PostRecord record = postRecordService.getById(id);
        User one = userService.getById(record.getUserId());
        record.setUserName(one.getNickName());
        record.setUserPic(one.getPic());
        record.setAge(one.getAge());
        record.setSex(one.getSex());
        if(postLikeRecordService.isLiked(userId,id)){
            record.setIsLiked(1);
        }else{
            record.setIsLiked(0);
        }
        return ResponseEntity.ok(record);
    }

    /**
     * 保存
     */
    @PutMapping("/save")
    @ApiOperation(value = "发布动态", notes = "发布动态")
    public ResponseEntity<Void> save(@RequestBody PostRecordParam postRecord) {
        PostRecord map = mapperFacade.map(postRecord, PostRecord.class);
        String userId = SecurityUtils.getUser().getUserId();
        map.setId(IdUtil.simpleUUID());
        map.setStatus(1);
        map.setIsDel(0);
        map.setUserId(userId);
        map.setCreateTime(new Date());
        map.setLikeNum(0);
        postRecordService.save(map);
        // postRecordMapper.insertOne(map);
        return ResponseEntity.ok().build();
    }

    /**
     * 删除
     */
    @DeleteMapping
    @ApiOperation(value = "删除动态", notes = "删除动态")
    public ResponseEntity<Void> delete(@RequestBody String[] ids) {
        for (String id : ids) {
            PostRecord p = new PostRecord();
            p.setId(id);
            p.setIsDel(1);
            postRecordService.updateById(p);
        }
        return ResponseEntity.ok().build();
    }


}

